package com.ruoyi.function.service.impl;

import com.github.binarywang.wxpay.bean.result.WxPayRefundV3Result;
import com.github.binarywang.wxpay.bean.result.WxPayUnifiedOrderV3Result;
import com.github.binarywang.wxpay.exception.WxPayException;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.TradeNoGenerator;
import com.ruoyi.demowechatpay.service.WxPayServiceV3;
import com.ruoyi.function.domain.Orders;
import com.ruoyi.function.domain.PayParam;
import com.ruoyi.function.domain.SysTopUp;
import com.ruoyi.function.domain.bo.OrdersBo;
import com.ruoyi.function.mapper.OrdersMapper;
import com.ruoyi.function.mapper.SysTopUpMapper;
import com.ruoyi.function.service.ISysTopUpService;
import com.ruoyi.function.service.IUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.List;
import java.util.Map;

/**
 * 系统充值订单Service业务层处理
 *
 * @author ruoyi
 * @date 2025-03-20
 */
@Slf4j
@Service
public class SysTopUpServiceImpl implements ISysTopUpService {
    @Autowired
    private SysTopUpMapper sysTopUpMapper;

    @Autowired
    private IUserService userService;
    @Autowired
    private WxPayServiceV3 wxPayServiceV3;
    @Autowired
    private OrdersMapper ordersMapper;

//    @Autowired
//    private PayService payService;


    /**
     * 查询系统充值订单
     *
     * @param topUpId 系统充值订单主键
     * @return 系统充值订单
     */
    @Override
    public SysTopUp selectSysTopUpByTopUpId(Long topUpId) {
        return sysTopUpMapper.selectSysTopUpByTopUpId(topUpId);
    }

    /**
     * 查询系统充值订单列表
     *
     * @param sysTopUp 系统充值订单
     * @return 系统充值订单
     */
    @Override
    public List<SysTopUp> selectSysTopUpList(SysTopUp sysTopUp) {
        return sysTopUpMapper.selectSysTopUpList(sysTopUp);
    }

    /**
     * 新增系统充值订单
     *
     * @param sysTopUp 系统充值订单
     * @return 结果
     */
    @Override
    public int insertSysTopUp(SysTopUp sysTopUp) {
        sysTopUp.setCreateTime(DateUtils.getNowDate());
        return sysTopUpMapper.insertSysTopUp(sysTopUp);
    }

    /**
     * 修改系统充值订单
     *
     * @param sysTopUp 系统充值订单
     * @return 结果
     */
    @Override
    public int updateSysTopUp(SysTopUp sysTopUp) {
        sysTopUp.setUpdateTime(DateUtils.getNowDate());
        return sysTopUpMapper.updateSysTopUp(sysTopUp);
    }

    /**
     * 批量删除系统充值订单
     *
     * @param topUpIds 需要删除的系统充值订单主键
     * @return 结果
     */
    @Override
    public int deleteSysTopUpByTopUpIds(Long[] topUpIds) {
        return sysTopUpMapper.deleteSysTopUpByTopUpIds(topUpIds);
    }

    /**
     * 删除系统充值订单信息
     *
     * @param topUpId 系统充值订单主键
     * @return 结果
     */
    @Override
    public int deleteSysTopUpByTopUpId(Long topUpId) {
        return sysTopUpMapper.deleteSysTopUpByTopUpId(topUpId);
    }


    public static long convertToCents(BigDecimal amount) {
        return amount.multiply(new BigDecimal("100"))
                .setScale(0, RoundingMode.HALF_UP)
                .longValueExact();
    }

    @Override
    public void processWxOrders(Map result) {

    }

    @Override
    public void processWxRefund(Map result) {

    }

    @Override
    public Map<String, String> topUp(PayParam payParam) {
        SysTopUp topUp = payParam.toTopUp();
        topUp.setTransactionId(TradeNoGenerator.generateOutTradeNo());
        Orders orders = ordersMapper.selectOrdersByOrderId(Long.valueOf(topUp.getOrderJson()));
        if (StringUtils.isNull(orders)) {
            throw new ServiceException(topUp.getOrderJson() + "订单编号不存在");
        }
        topUp.setTotal(orders.getTotalAmount());
        int i = sysTopUpMapper.insertSysTopUp(topUp);
        if (i <= 0) {
            throw new ServiceException("操作失败,请重试");
        }
// 获取当前用户id
        Long userId = SecurityUtils.getUserId();
        //拉起支付
        SysUser userById = userService.getUserById(userId);
        try {
            Map<String, String> wxPayUnifiedOrderV3Result = wxPayServiceV3.packageJsapiPay(userById.getOpenid(), topUp.getTransactionId(), orders.getTotalAmount(), "订单商品");
        return wxPayUnifiedOrderV3Result;
        } catch (Exception e) {
            log.info("{}支付失败。报错原因{}", orders.getOrderId(), e.getMessage());
            throw new RuntimeException(e);
        }


    }

    @Override
    public Map<String, String> pullUpPayment(OrdersBo ordersBo) {
        SysTopUp topUp = new SysTopUp();
        topUp.setTransactionId(TradeNoGenerator.generateOutTradeNo());
        topUp.setTotal(ordersBo.getTotalAmount());
        topUp.setOrderJson(ordersBo.getOrderId().toString());
        topUp.setOrderType("merge");
        int i = sysTopUpMapper.insertSysTopUp(topUp);
        if (i <= 0) {
            throw new ServiceException("操作失败,请重试");
        }
        //拉起支付
        SysUser userById = userService.getUserById(ordersBo.getUserId());
        try {
            Map<String, String> wxPayUnifiedOrderV3Result = wxPayServiceV3.packageJsapiPay(userById.getOpenid(), topUp.getTransactionId(), ordersBo.getTotalAmount(), "订单商品");
            wxPayUnifiedOrderV3Result.put("orderId", String.valueOf(ordersBo.getOrderId()));
            return wxPayUnifiedOrderV3Result;
        } catch (WxPayException e) {
            log.info("{}支付失败。报错原因：{}", ordersBo.getOrderId(), e.getMessage());
            throw new RuntimeException(e);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

    }

    @Override
    public int orderRefund(Orders order) {
        SysTopUp sysTopUp = sysTopUpMapper.selectSysTopUpByOrderId(order.getOrderId());
        if (StringUtils.isNull(sysTopUp)){
            Long parentOrder = order.getParentOrder();
            if (parentOrder != null){
                sysTopUp = sysTopUpMapper.selectSysTopUpByOrderId(parentOrder);
            }
        }
        if (StringUtils.isNull(sysTopUp)){
            throw new ServiceException("订单编号不存在");
        }
        //拉起退款
        try {
            WxPayRefundV3Result result = wxPayServiceV3.refund( sysTopUp.getTransactionId(),TradeNoGenerator.generateOutTradeNo(), sysTopUp.getTotal().abs(), sysTopUp.getTotal().abs(), "订单退款");
        } catch (WxPayException e) {
            log.info("{}退款失败。报错原因{}", order.getOrderId(), e.getMessage());
            throw new RuntimeException(e);

        }
        return 1;
    }

    @Override
    public SysTopUp selectSysTopUpByTransactionId(String outTradeNo) {
        return sysTopUpMapper.selectSysTopUpByTransactionId(outTradeNo);
    }
}
